import PySimpleGUI as sg
import requests


class Fanyi:
    def __init__(self):
        self.headers = {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1",
            "cookie": "BIDUPSID=29B162E39BE7F5DB9AF18DD094DB9A78; PSTM=1592488843; BAIDUID=29B162E39BE7F5DBE9307BDB9AF7BC26:FG=1; MCITY=-340%3A; BDUSS=HZldVZBSE1RRTNnMGZWMXAxMUlLNmpSRXBkbUxvNjBzV1dVYzJ1OUVsNks0aUpmSVFBQUFBJCQAAAAAAQAAAAEAAACxkzsF0fS54rXEU0hVQUlqaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIpV-16KVfteO; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; cflag=13%3A3; BDRCVFR[VXHUG3ZuJnT]=mk3SLVN4HKm; delPer=0; PSINO=7; H_PS_PSSID=; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; Hm_lvt_afd111fa62852d1f37001d1f980b6800=1593683351,1593768315; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1593682335,1593685161,1593768315; yjs_js_security_passport=17cec1af5aa4f1d6f3909cce4d45fb099ee68a3c_1593768317_js; Hm_lpvt_afd111fa62852d1f37001d1f980b6800=1593768397; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1593768397"}

        self.url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

        sg.theme('GreenTan')  # give our window a spiffy set of colors

        self.layout = [[sg.Text('文本输入框',font='20px')],
          [sg.Multiline(size=(70, 3), enter_submits=False, key='input_words', do_not_clear=False)],
          [sg.Button("点击翻译",focus=True,key='fanyi',bind_return_key=True,button_color=(sg.YELLOWS[0], sg.GREENS[0]))],
          [sg.Text('翻译内容输出框',font='20px')],
          [sg.Output(size=(70, 6), font=('Helvetica 12'))]]

        self.window = sg.Window('汉英翻译器', self.layout, font=('Helvetica', '10'), default_button_element_size=(8, 2))

    def parse_html(self, url, data):
        r = requests.post(url, data=data, headers=self.headers)
        return r.json()

    def translate(self):
        try:
            self.tra_str = self.value['input_words'].rstrip()
            # 2.准备翻译的post的data
            data = {'i': self.tra_str,
                    'from': 'AUTO',
                    'to': 'AUTO',
                    'smartresult': 'dict',
                    'client': 'fanyideskweb',
                    'doctype': 'json',
                    'version': '2.1',
                    'keyfrom': 'fanyi.web',
                    'action': 'FY_BY_REALTIME',
                    'typoResult': 'false'}
            # 3.发出请求
            tra_json = self.parse_html(self.url, data)
            result = tra_json['translateResult'][0][0]['tgt']
            print('翻译结果为：{}'.format(result))
        except:
            pass

    def circle_event(self):
        while True:  # The Event Loop
            self.event, self.value = self.window.read()
            if self.value['input_words']=='\n':
                sg.popup("请输入内容")
            if self.event in (sg.WIN_CLOSED, 'EXIT'):  # quit if exit button or X
                break
            if self.event == 'fanyi':
                self.translate()
        self.window.close()

if __name__ == '__main__':
    fanyi = Fanyi()
    fanyi.circle_event()



